#!/bin/bash

admin_list="zhiwen.liu@jrdcom.com raffi.semerciyan@jrdcom.com"

function print_usage()
{
   # ./imei.sh /data/samba_share/imei/ simgen_db simgen '[Simgen01]!simgeN' > /tmp/imei.sh.log
   echo "Usage: $0 <path> <dbname> <dblogin> <dbpassword> <remote host>"
   echo "Manage imei request from Unlock Tool"
}

# list request in remote server
function getList()
{
    # ./ssh_getlist.sh 172.24.61.53 root /data/home/simlock/simlock_requests/send > request_list
    r_host=$1
    r_login=$2
    r_dir=$3

    . /data/home/simgen/.bashrc
    #/data/scripts/ssh_getlist.sh $r_host $r_login $r_dir
    ./ssh_getlist.sh $r_host $r_login $r_dir
}

# get request file from remote server only if has not already been uploaded
function getFile()
{
    # ./ssh_getfile.sh 172.24.61.53 root /data/samba_share/imei/in/

    r_host=$1
    r_login=$2

    . /data/home/simgen/.bashrc
    #/data/scripts/ssh_getfile.sh $r_host $r_login $pathin
    ./ssh_getfile.sh $r_host $r_login $pathin
}

# put result file on remote server
function putFile()
{
    # ./ssh_putfile.sh 172.24.61.53 root /data/home/simlock/simlock_requests/receive/

    r_host=$1
    r_login=$2
    r_folder=$3

    . /data/home/simgen/.bashrc
    #/data/scripts/ssh_putfile.sh $r_host $r_login $r_folder
    ./ssh_putfile.sh $r_host $r_login $r_folder
}

function getFullTextMsg()
{
    case "$1" in
	not_locked)
	    echo "Not Simlocked"
	    ;;
	bad_format)
	    echo "Bad Format"
	    ;;
	bad_checksum)
	    echo "Bad Checksum"
	    ;;
	not_alcatel-tct_mobile_phone)
	    echo "Not a TCT Mobile Phone"
	    ;;
	sender_not_allowed)
	    echo "Sender not Allowed"
	    ;;
    esac
}

function getPath()
{
    case "$1" in
	0)
	    echo "in/done/"
	    ;;
	2)
	    echo "in/skipped/"
	    ;;
	1)
	    echo "in/error/"
	    ;;
	*)
	    echo "in/error/"
	    ;;
    esac
}

function deleteTmp()
{
    if [ -f $1 ];then
	`rm -f $1`
    fi
}

path=$1
dbname=$2
dblogin=$3
dbpassword=$4
r_host=$5

tmpfile="request_list"

pathin=$path"in"
pathskipped=$pathin"/skipped"
patherror=$pathin"/error"

if [ "x$r_host" == "x" ]; then
   echo "`date +'%Y/%m/%d %H:%M:%S'` [ERROR] All arguments not available."
   print_usage
   exit 1
fi

lockfile="/tmp/imei.lock" 
echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: Checking lock file $lockfile..."
if [ -f $lockfile ]; then 
    echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: Lock file exits! Aborting..." 
    exit
fi

echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: Creating lock file..."
`touch $lockfile` 

let "total_processed_file_counter=0"
let "skipped_processed_file_counter=0"
let "error_processed_file_counter=0"
let "new_processed_file_counter=0"

echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: Processing... "

echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: Retrieving REQUEST files from remote Server..."
#echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: Retrieving list..."
#getList 172.24.61.53 simlock /data/home/simlock/simlock_requests/send > $tmpfile
getList $r_host simlock /data/Files/Send > $tmpfile
#cat $tmpfile
#echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: Retrieving files..."
getFile $r_host simlock $pathin

tmpfile1=/tmp/imei.tmp1 # contains the list of files to process
#tmpfile2=/tmp/imei.tmp2
tmpfile3=/tmp/imei.tmp3 # imei list - sent as parameters to the perl script
tmpfile4=/tmp/imei.tmp4 # contains the result returned by the perl script 

echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: Listing files in $pathin... "
find $pathin -maxdepth 1 | grep request_ > $tmpfile1 

C=`cat $tmpfile1 | wc -l`
if [ $C -eq 0 ]; then
    echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: No file found."
else

    #cat $tmpfile1 | sed >$tmpfile2 s/\ [\ ]*/\+/g
    
    for i in `cat $tmpfile1`
      do
      # validate infile format
      nbLineIn=`wc -l $i | awk -F " " '{ print $1 }'`
      lastLineIn=`tail -1 $i`
      
      #echo "nbLineIn -> $nbLineIn lastLineIn -> $lastLineIn"
      #diffIn=`$((nbLineIn-lastLineIn))`
      let "diffIn=$nbLineIn-$lastLineIn"
      #echo "I'm here"
      #echo $diffIn
      if [ $diffIn -ne 1 ];then
	  echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: [ERROR] File "`basename $i`" has a Wrong format. Skipping..."
          `mv "$i" $patherror`
	  continue
      fi

      bi=`basename $i`
      requestid=`echo $bi | sed s/request_// | sed s/.txt//`
      #echo $requestid
            
      echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: Processing $bi... "
      let "total_processed_file_counter=$total_processed_file_counter+1"

      if [ -f $tmpfile3 ]; then 
	  `rm $tmpfile3`
      fi  

      #if [ -f $i ]; then
	  #let "skipped_processed_file_counter=$skipped_processed_file_counter+1"
	  #echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: File already processed. Skipping... "
	  #echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: File will be moved to $pathskipped."
          #`mv "$i" $pathskipped`
	  #continue
      #fi

      # extract requester from request file
      # will be sent to perl script as parameter
      requester=`head -1 $i | awk -F ";" '{ print $2 }'`

      # extract IMEI from request file
      # will be sent to perl script as parameter
      for j in `cat $i`
	do
	echo $j | awk -F ";" '{ print $3 }' >> $tmpfile3
      done
      
      # The following script will try to retrieve the unlock keys from DB
      # If he finds them, then he print them to STDOUT with the following
      # format: <IMEI>;<key1>;<key2>;<key3>;<key4>;<key5>;<key6>
      #
      # If not found, then the format should be:
      # <IMEI>;;;;;;
      #
      #
      # If imei is not lock, then you should get:
      # <IMEI>;not_locked;;;;;;

      #perl /data/scripts/imei.pl $dbname $dblogin $dbpassword $requester `cat $tmpfile3` > $tmpfile4 2>&1
      perl imei.pl $dbname $dblogin $dbpassword $requester `cat $tmpfile3` > $tmpfile4 2>&1
      
      res=$?

      # res=0  -> process ok
      # res=1  -> error while processing
      
      if [ $res -ne 0 ];then
	  echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: ERROR CODE=$res"
      fi
      
      #if [ $res -eq 3 -o $res -eq 1 -o $res -eq 2 -o $res -eq 12 ]; then
      if [ $res -eq 1 ]; then
	  pathout=$path`getPath $res`
	  let "error_processed_file_counter=$error_processed_file_counter+1"
	  echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: File will be moved to $pathout."
	  `mv "$i" $pathout`
	  	  
      elif [ $res -eq 0 ]; then
	  let "new_processed_file_counter=$new_processed_file_counter+1"
	  echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: Done."
	  pathout=$path`getPath $res`
	  echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: File will be moved to $pathout."
	  `mv "$i" $pathout`
	  
      else 
	  let "error_processed_file_counter=$error_processed_file_counter+1"
	  pathout=$path`getPath $res`
	  echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: File will be moved to $pathout."
	  `mv "$i" $pathout`
	  
      fi

      # if perl script returned no error
      if [ $res -eq 0 ];then 
	  
          # build both f1/f2 result file
	  #cat $tmpfile4

	  for k in `cat $tmpfile4`
	    do
	    #echo $k
	    l=""
	    #echo "k is $k"

	    field2=`echo $k | awk -F ";" '{ print $2 }'`
	    #echo "field2: "$field2

	    # rewrite the line to display full text message
	    if [ "$field2" == "not_locked" -o "$field2" == "bad_format" -o "$field2" == "bad_checksum" -o "$field2" == "not_alcatel-tct_mobile_phone" -o "$field2" == "sender_not_allowed" ];then
		fullTextMsg=`getFullTextMsg  $field2`
		#echo "fullTextMsg "$fullTextMsg
		l=`echo $k | sed s/$field2/"$fullTextMsg"/`
		#echo "after rewriting msg l=$l"
	    else
		l=$k
	    fi

            # check whether the key is bad
	    imei=`echo $k | awk -F ";" '{ print $1 }'`
	    badKey=`find $path -name $bi -exec grep $imei {} \; | awk -F";" '{ print $4 }'`

	    if [ "Y$badKey" != "Y" ];then
		#echo "bad key is $badKey"
		l=`echo $k | perl -e 'while (<STDIN>) { $_=~s/([^;]*;)([^;]*)(;.*)/$1;;;;;;/;print;  }'`
		#echo "after checking bad key l=$l"
		echo $requestid";"$requester";"$l >> $path"out/result_f2_"$requestid".txt"
	    fi

	    echo $requestid";"$requester";"$l >> $path"out/result_f1_"$requestid".txt"
	    #echo $field2
	    if [ "x$field2" == "x" -a "Y$badKey" == "Y" ];then
		echo $requestid";"$requester";"$l >> $path"out/result_f2_"$requestid".txt"
	    fi

	  done
      fi

      # validate outfile format
      nbLineOut=`wc -l  $path"out/result_f1_"$requestid".txt" | awk -F " " '{ print $1 }'`
      #nbLineOut=`wc -l  $path"out/result_f1_"$requestid".txt" | awk '{ print $1 }'`
      #echo "$lastLineIn $nbLineOut"
      #diffOut=$((lastLineIn-nbLineOut))
      let "diffOut=$lastLineIn-$nbLineOut"
      #echo $diffOut
      if [ $diffOut -ne 0 ];then
	  echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: [ERROR] Format not expected. Skipping..."
	  continue
      fi

      # adding number of lines to f1
      echo $lastLineIn >> $path"out/result_f1_"$requestid".txt"

      # if f2 exists then a manual treatment will be done
      if [ -f $path"out/result_f2_"$requestid".txt" ]; then 

          # adding number of lines to f2
	  f2NbLine=`wc -l  $path"out/result_f2_"$requestid".txt" | awk -F " " '{ print $1 }'`
	  echo "$f2NbLine" >> $path"out/result_f2_"$requestid".txt"

      fi
      
      mkdir -p "/tmp/request/request_"$requestid
      
      if [ -f $path"out/result_f2_"$requestid".txt" ]; then 
          # change file format
	  unix2dos $path"out/result_f2_"$requestid".txt" > /dev/null 2>&1
	  
	  cp $path"out/result_f2_"$requestid".txt" "/tmp/request/request_"$requestid
      fi
      
      # change file format
      unix2dos $path"out/result_f1_"$requestid".txt" > /dev/null 2>&1
      
      cp $path"out/result_f1_"$requestid".txt" $pathout$bi "/tmp/request/request_"$requestid
      cd "/tmp/request/request_"$requestid; tar -cf "request_"$requestid".tar.gz" *
      cd /data/scripts/
      
      
	  #/data/scripts/sendmail.pl -f multisimgen.support@tcl.com -t frederic.chailloux@jrdcom.com -s "Multisimgen Request #$requestid>imei.sh< f2 notification" $path"out/request_f2_"$requestid".txt"
	  #/data/scripts/sendmail.php multisimgen.support\@tcl.com "[ Request #: $requestid ] Unlock codes request" $path"out/result_f2_"$requestid".txt" frederic.chailloux\@jrdcom.com
	  echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: Sending Mail..."
	  #/data/scripts/sendmail.php multisimgen.support\@tcl.com "[ Request #: $requestid ] Unlock codes request" "/tmp/request/request_"$requestid"/request_"$requestid".tar.gz" frederic.chailloux\@jrdcom.com
	  for admin in $admin_list
	  do
	      ./sendmail.php multisimgen.support\@tcl.com "[ Request #: $requestid ] Unlock codes request" "/tmp/request/request_"$requestid"/request_"$requestid".tar.gz" $admin
	  done
      #fi  

    done
    
    # uploading files to remote server
    #putFile 172.24.61.53 simlock /data/home/simlock/simlock_requests/receive/
    putFile $r_host simlock /data/Files/Receive

    # deleting temp files
    deleteTmp $tmpfile
    deleteTmp $tmpfile1
    deleteTmp $tmpfile3
    deleteTmp $tmpfile4

    # deleting tmp folder
    `rm -Rf /tmp/request/*`

    # deleting result files because contain keys (commented out for testing)
    find /data/samba_share/imei/out -name result_\* -exec mv {} /data/samba_share/imei/done \; 
    
fi
    
echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: End of Process."
echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: ### Summary: #################################################"
echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: Total file Processed: $total_processed_file_counter"
echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT:     Included skipped: $skipped_processed_file_counter"
echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT:       Included error: $error_processed_file_counter"
echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT:         Included new: $new_processed_file_counter"
echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: ##################################"

echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: Deleting lock file..."
`rm $lockfile` 

error=`grep "\[ERROR\]" /tmp/imei.sh.log`
res=$?
if [ $res -eq 0 ]; then
    #/data/scripts/sendmail.pl -f multisimgen.support@tcl.com -t frederic.chailloux@jrdcom.com -s "Multisimgen IMEI Request >imei.sh< notification" /tmp/imei.sh.log
    for admin in $admin_list
    do
      ./sendmail.pl -f multisimgen.support@tcl.com -t $admin -s "Multisimgen IMEI Request >imei.sh< notification" /tmp/imei.sh.log
    done
fi
